package workqueues;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeoutException;

/**
 *  消费者
 */
public class Worker {
    private final static String TASK_QUEUE_NAME = "task_queue";
    public static void main(String[] args) throws Exception {
        // 加载配置文件
        Properties properties = new Properties();
        properties.load(NewTask.class.getClassLoader().getResourceAsStream("application.properties"));
        // 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 设置RabbitMQ地址
        factory.setHost(properties.getProperty("rabbitmq.host"));
        factory.setUsername(properties.getProperty("rabbitmq.username"));
        factory.setPassword(properties.getProperty("rabbitmq.password"));
        // 创建一个新的连接
        Connection connection = factory.newConnection();
        // 创建一个通道
        Channel channel = connection.createChannel();
        // 声明一个队列
        channel.queueDeclare(TASK_QUEUE_NAME,true,false,false,null);
        System.out.println("Worker Waiting Received messages");

        channel.basicQos(1);// 保证一次只分发一个,限制发送给同一个消费者不得超过一条消息
        // 创建消费者，关闭自动应答，改为手动应答
        channel.basicConsume(TASK_QUEUE_NAME,false, new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, com.rabbitmq.client.Envelope envelope, com.rabbitmq.client.AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body,"UTF-8");
                System.out.println("Worker Received '" + message + "'");
                try {
                    doWork(message);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    System.out.println("Worker Done");
                    channel.basicAck(envelope.getDeliveryTag(),false);// 手动应答
                }
            }
        });
    }
    private static void doWork(String task) throws InterruptedException {
        for (char ch: task.toCharArray()) {
            if (ch == '.') Thread.sleep(1000);
        }
    }
}
